package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"log"
	"os"
	"protobuf-learn/internal/config"
	"protobuf-learn/proto"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

func main() {
	ctx := context.Background()

	// load tls from privite CA
	certPool := x509.NewCertPool()
	cert, err := os.ReadFile("certs/ca.crt")
	if err != nil {
		log.Fatal(err)
	}
	if ok := certPool.AppendCertsFromPEM(cert); !ok {
		log.Fatal("failed to append CA cert")
	}

	clientCert, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")
	if err != nil {
		log.Fatal(err)
	}

	tlsConfig := &tls.Config{
		Certificates: []tls.Certificate{clientCert},
		RootCAs:      certPool,
	}

	tlsCredentials := credentials.NewTLS(tlsConfig)

	host := ":50051"

	serviceConfig := &config.Config{
		MethodConfig: []config.MethodConfig{
			{
				Name: []config.NameConfig{
					{
						Service: "config.ConfigService",
					},
				},
				RetryPolicy: config.RetryPolicy{
					MaxAttempts:          4,
					InitialBackoff:       "1s",
					MaxBackoff:           "10s",
					BackoffMultiplier:    2,
					RetryableStatusCodes: []string{"INTERNAL", "UNAVAILABLE"},
				},
			},
		},
	}
	serviceConfigStr, err := json.Marshal(serviceConfig)
	if err != nil {
		log.Fatalf("failed to marshal config: %v", err)
	}
	conn, err := grpc.NewClient(host,
		grpc.WithTransportCredentials(tlsCredentials),
		grpc.WithDefaultServiceConfig(string(serviceConfigStr)),
	)

	if err != nil {
		log.Fatal(err)
	}

	defer conn.Close()

	client := proto.NewConfigServiceClient(conn)

	_, err = client.Flaky(ctx, &proto.FlakyRequest{})
	if err != nil {
		log.Fatal(err)
	}
}
